// See Audio.h for description

#include "Audio.h"

// Globals

bool Audio::init_audio()
{
	if ( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 ) return false;

	return true;
}

void Audio::cleanup_audio()
{
	Mix_CloseAudio();
}

// Note: Settings loops to -1 will repeat until stopped
void Audio::Play( Audio::Music* music, int loops )
{
	if ( Mix_PlayMusic( music->music, loops ) == -1 ) throw "Error playing music.";
}

void Audio::Play( Audio::Sound* sound, int loops )
{
	if ( Mix_PlayChannel( -1, sound->chunk, loops ) == -1 ) throw "Error playing sound.";
}

// Music

Audio::Music::Music()
{
	this->music = NULL; // Initialize the pointer to NULL to avoid potential issues
}

Audio::Music::Music( std::string filepath )
{
	this->music = NULL; // Initialize the pointer to NULL to avoid potential issues

	this->music = Mix_LoadMUS( filepath.c_str() );
	if ( this->music == NULL ) throw "Unable to load music.";
}

Audio::Music::~Music()
{
	Mix_FreeMusic( this->music );
}

void Audio::Music::Pause()
{
	if ( Mix_PlayingMusic() != 0)
	{
		// there is music playing (or paused)
		if ( Mix_PausedMusic() != 0 ) return; // The music is already paused
		else
		{
			Mix_PauseMusic();
		}
	}
}

void Audio::Music::Resume()
{
	if ( Mix_PlayingMusic() != 0 )
	{
		// there is music playing (or paused)
		if ( Mix_PausedMusic() != 0 )
		{
			// there is paused music
			Mix_ResumeMusic();
		}
	}
}

void Audio::Music::Stop()
{
	if ( Mix_PlayingMusic() != 0 )
	{
		Mix_HaltMusic();
	}
}

// Sound

Audio::Sound::Sound()
{
	this->chunk = NULL; // Initialize the pointer to NULL to avoid potential issues
}

Audio::Sound::Sound( std::string filepath )
{
	this->chunk = NULL; // Initialize the pointer to NULL to avoid potential issues

	this->chunk = Mix_LoadWAV( filepath.c_str() );
	if ( this->chunk == NULL ) throw "Unable to load sound.";
}

Audio::Sound::~Sound()
{
	Mix_FreeChunk( this->chunk );
}